
#import "Player.h"
#import "GameManager.h"

@implementation Player

- (void) additionalSetup {
    type = PLAYER;  
    Tex *tex = [[GameManager getInstance] getTex: @"cockpit.png" isImage: YES];
    textureID = [tex getTextureID];     
    radius = 15;
    speedOffset = 0;   
    hitCnt = 0;
   
    w = [tex getWidth] / [tex getHeight];      
    h = 1; 
        
    GLfloat verticesObjData[ ] = {       
        0,    h, 0, 
        w,    h, 0, 
        0,    0, 0, 
        w,    0, 0  
    };    
    
    GLfloat textureCoordsObjData[ ] = { 
        1, 0, 0, 
        0, 0, 0,
        1, 1, 0, 
        0, 1, 0  
    };    
    
    GLfloat normalsObjData[ ] = {     
        0, 0, 1,
        0, 0, 1,
        0, 0, 1,
        0, 0, 1
    };    
    
    [self setVertices: verticesObjData
                 size: sizeof(verticesObjData) 
         setTexCoords: textureCoordsObjData
                 size: sizeof(textureCoordsObjData)
           setNormals: normalsObjData
                 size: sizeof(normalsObjData)
             setFaces: nil
                 size: 0];   
}

- (void) draw {     
    
    timer++;
    if (timer % 15 == 0 && [[GameManager getInstance] getState] != GAME_OVER) {
        [[GameManager getInstance] createSprite: BULLET]; 
    }  
    
    if (touchAction) { 
        speedOffset += 1;
        if (speedOffset > 10) speedOffset = 10;
        
        int x = W/2;
        int y = H/2;
        
        int n1 = y - x;
        int n2 = y + x;    
        int np1 = touchPoint.y - touchPoint.x;
        int np2 = touchPoint.y + touchPoint.x;    
        
        if (np1 < n1 && np2 < n2) { pos.y += speedOffset; } //UP
        if (np1 > n1 && np2 > n2) { pos.y -= speedOffset; } //DOWN
        if (np1 > n1 && np2 < n2) { pos.x += speedOffset; } //LEFT
        if (np1 < n1 && np2 > n2) { pos.x -= speedOffset; } //RIGHT
    } else {
        speedOffset = 1;
    }
               
    pos.z+=5; 
    

    [[GameManager getInstance] setCameraX: pos.x cameraY: pos.y cameraZ: pos.z
                                  lookAtX: pos.x lookAtY: pos.y lookAtZ: pos.z+1]; 
    
    [super renderSprite]; 
}

- (void) move {     
    glTranslatef(pos.x - 0.5, pos.y - 0.752, pos.z + 1.59);
}

- (void) hit {
    hitCnt++;
    if (hitCnt == 3) {
        [[GameManager getInstance] setState: GAME_OVER];
        [[GameManager getInstance] createOGLText: @"GAME OVER" 
                                         offsetX: 2.1
                                         offsetY: 2 
                                     selfDestroy: NO];
    }
}

- (void) hitCapsule {
    hitCnt--;
    if (hitCnt < 0) hitCnt = 0;
}

- (void) setTouch: (CGPoint) p {
    touchAction = true;
    touchPoint = p;    
}

- (void) touchEnded {
    touchAction = false;
}

@end
